package it.unical.mat.aec.persistence;

import it.unical.mat.aec.model.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class TestFileManagerSingleton {
	
	/*public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		Domanda d1=new Domanda(1, "ciao", "ei", 1);
		Domanda d2=new Domanda(2, "cia", "i", 3);
		Traccia traccia=new Traccia(1);
		traccia.aggiungiDomanda(d1);
		traccia.aggiungiDomanda(d2);
		Test t1=new Test(1, traccia, new Studente(123),1 );
		t1.aggiungiDomanda(d1);
		t1.aggiungiDomanda(d2);
		Test t2=new Test(2, traccia, new Studente(12),1 );
		t2.aggiungiDomanda(d1);
		t2.aggiungiDomanda(d2);
		ArrayList<Test> tests=new ArrayList<Test>();
		tests.add(t1);
		tests.add(t2);
		TestFileManagerSingleton.getInstance().salvaTests("prova", tests);
		ArrayList<Test> tests=TestFileManagerSingleton.getInstance().caricaTests("prova");
		for(Test t:tests)
			System.out.println(t.getId()+" "+t.getDomande().get(0).getTesto());
	}*/
	
	private static TestFileManagerSingleton fileManager;
	
	private TestFileManagerSingleton() {
		
	}
	
	public static TestFileManagerSingleton getInstance(){
		if(fileManager==null)
			fileManager=new TestFileManagerSingleton();
		return fileManager;
	}
	
	public ArrayList<Test> caricaTests(String path) throws FileManagerException {
		ArrayList<Test> tests=new ArrayList<Test>();
		ObjectInputStream reader;
		try {
			reader = new ObjectInputStream(new FileInputStream(new File(path)));
			Object obj=null;
			while((obj=reader.readObject())!=null){
				if(obj instanceof Test)
					tests.add((Test) obj);
			}
			reader.close();
		} catch (Exception e) {
			throw new FileManagerException(e.getLocalizedMessage());
		}
		return tests;
	}
	
	public void salvaTests(String nomeFile,ArrayList<Test> tests) throws FileManagerException {
		ObjectOutputStream writer;
		try {
			writer = new ObjectOutputStream(new FileOutputStream(nomeFile));
			for(Test t:tests){
				writer.writeObject(t);
			}
			//scrive null come EOF
			writer.writeObject(null);
			writer.close();
		} catch (Exception e) {
			throw new FileManagerException(e.getLocalizedMessage());
		}
	}
	
	public void cancellaTests(String path){
		File file=new File(path);
		file.delete();
	}

}
